package com.hzy.oplus.hook.fragment;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hzy.oplus.hook.R;
import com.hzy.oplus.hook.bean.LoginData;
import com.hzy.oplus.hook.bean.LoginResult;
import com.hzy.oplus.hook.bean.ProjectItem;
import com.hzy.oplus.hook.bean.RefreshQrResult;
import com.hzy.oplus.hook.event.LoginEvent;
import com.hzy.oplus.hook.utils.EncodeUtil;
import com.hzy.oplus.hook.utils.MD5;
import com.hzy.oplus.hook.utils.UrlConstants;
import com.hzy.oplus.hook.utils.UserUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by huzongyao on 2018/12/30.
 */

public class LoginDialogFragment extends DialogFragment
        implements TextWatcher, View.OnClickListener {

    private View mRootView;
    private EditText mEditName;
    private EditText mEditPassword;
    private Button mButtonLogin;
    private ProgressDialog mProgressDialog;

    public static void showDialog(FragmentManager manager) {
        if (manager == null) {
            return;
        }
        LoginDialogFragment fragment = new LoginDialogFragment();
        fragment.show(manager, "dialog");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setLayout(-1, -2);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @SuppressWarnings("unused")
    public void onLoginFinished(LoginEvent event) {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        if (event.loginResult != null) {
            String message = event.loginResult.describe;
            if (!StringUtils.isTrimEmpty(message)) {
                ToastUtils.showShort(message);
            }
            if (event.loginResult.code.equals("000")) {
                dismiss();
            }
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isAdded() && mEditName != null) {
            String name = UserUtils.loadUserName();
            mEditName.setText(name);
            mEditName.setSelection(name.length());
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.dialog_fragment_login, null);
        Window window = getDialog().getWindow();
        if (window != null) {
            window.requestFeature(Window.FEATURE_NO_TITLE);
        }
        mEditName = mRootView.findViewById(R.id.edit_name);
        mEditPassword = mRootView.findViewById(R.id.edit_password);
        mButtonLogin = mRootView.findViewById(R.id.button_login);
        mEditName.addTextChangedListener(this);
        mEditPassword.addTextChangedListener(this);
        mButtonLogin.setOnClickListener(this);
        return mRootView;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (isAdded()) {
            if (StringUtils.isTrimEmpty(mEditName.getText().toString()) ||
                    StringUtils.isTrimEmpty(mEditPassword.getText().toString())) {
                mButtonLogin.setEnabled(false);
            } else {
                mButtonLogin.setEnabled(true);
            }
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.button_login) {
            doStartLogin();
        }
    }

    private void doStartLogin() {
        if (!isAdded()) {
            return;
        }
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.show();
        String name = mEditName.getText().toString().trim();
        String password = mEditPassword.getText().toString().trim();
        String passwordMd5 = MD5.getMD5(password);
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(8, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("sys_language", EncodeUtil.getLanguage())
                .add("cVersion", UrlConstants.APP_VERSION)
                .add("sys_source", "2")
                .add("info", EncodeUtil.getSysInfoString())
                .add("cType", UrlConstants.CLIENT_TYPE)
                .add("account", name)
                .add("userPwd", passwordMd5)
                .build();
        Headers headers = new Headers.Builder()
                .build();
        Request request = new Request.Builder()
                .url(UrlConstants.LOGIN_URL)
                .headers(headers)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                LoginEvent event = new LoginEvent();
                EventBus.getDefault().post(event);
            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String respString = response.body().string();
                    LoginResult loginResult = JSON.parseObject(respString, LoginResult.class);
                    if (loginResult != null && loginResult.isLogin()) {
                        refreshQrCount(respString, loginResult);
                        UserUtils.saveUserName(name);
                    } else {
                        EventBus.getDefault().post(new LoginEvent());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    EventBus.getDefault().post(new LoginEvent());
                }
            }
        });
    }


    private void refreshQrCount(String respString, LoginResult loginResult) {
        LoginData loginData = loginResult.data;
        String token = loginData.token;
        String userId = loginData.id;
        String projectId = "";
        List<ProjectItem> projectList = loginData.projectList;
        if (projectList != null && projectList.size() > 0) {
            projectId = projectList.get(0).id;
        }
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(8, TimeUnit.SECONDS)
                .addInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BODY))
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("sys_projectId", projectId)
                .add("sys_language", EncodeUtil.getLanguage())
                .add("sys_userId", userId)
                .add("sys_source", "2")
                .add("info", EncodeUtil.getSysInfoString())
                .add("token", token)
                .add("qrNum", UserUtils.getPassCode())
                .build();
        Headers headers = new Headers.Builder()
                .build();
        Request request = new Request.Builder()
                .url(UrlConstants.REFRESH_QR_URL)
                .headers(headers)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                EventBus.getDefault().post(new LoginEvent());
            }

            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String rString = response.body().string();
                    RefreshQrResult rResult = JSON.parseObject(rString, RefreshQrResult.class);
                    if (rResult.code.equals("000")) {
                        UserUtils.saveLoginData(respString);
                        EventBus.getDefault().post(new LoginEvent(loginResult));
                    } else {
                        EventBus.getDefault().post(new LoginEvent());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    EventBus.getDefault().post(new LoginEvent());
                }
            }
        });
    }
}
